package com.itlaobing.process;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet( "/sign/in" )
public class SignInServlet extends HttpServlet {

	private static final long serialVersionUID = -4004708609510318590L;
	
	private final String filename = "user.properties";
	
	private String username ;
	private String password ;
	
	private void read() {
		Class<?> c = this.getClass() ; // 获得当前对象的类型
		// 通过 Class 类中的 getResourceAsStream 方法可以获得一个字节输入流
		InputStream in = c.getResourceAsStream( filename ); // 用于读取与c所表示的类在同一个包中的指定名称的文件
		Properties props = new Properties();
		try {
			props.load( in );
		} catch (IOException e) {
			e.printStackTrace();
		}
		this.username = props.getProperty( "username" );
		this.password = props.getProperty( "password" );
	}

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 设置请求对象(req)和响应对象(resp)的编码
		req.setCharacterEncoding( "UTF-8" );
		resp.setCharacterEncoding( "UTF-8" );
		
		// 调用自定义的read方法读取properties文件中的 用户名 和 密码
		this.read();
		
		// 接受来自客户端(比如浏览器)的数据
		String uname = req.getParameter( "username" ); // 根据请求参数的名称获取请求参数的值
		String passwd = req.getParameter( "password" );
		
		// 获取输出流之前，先设置 MIME 类型
		resp.setContentType( "text/html;charset=UTF-8" );
		
		// 获得可以向响应对象中输出数据的字符打印流
		PrintWriter w = resp.getWriter();
		
		if( username.equals( uname ) && password.endsWith( passwd ) ) {
			w.println( "<h1 align='center'>" );
			w.println( "欢迎" + username  );
			w.println( "<h1>" );
		} else {
			w.println( "<h1>你的用户名必须是" + this.username + "</h1>" );
			w.println( "<h1>你的密码必须是" + this.password + "</h1>" );
			w.println( "<a href='/sign-in.html'>返回</a>" );
		}
		
	}

}
